package com.wisty.finalproject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.R.integer;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;

public class MainActivity extends FragmentActivity {
	
	private UiLifecycleHelper uiHelper;
	private Session.StatusCallback callback = 
	    new Session.StatusCallback() {
	    @Override
	    public void call(Session session, 
	            SessionState state, Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};
	
	private boolean isResumed = false;
	
	private MenuItem log_out;
	private MenuItem sort;
	
	private static final int SPLASH = 0;
	private static final int SELECTION = 1;
	private static final int SETTINGS = 2;
	private static final int FRAGMENT_COUNT = SETTINGS +1;
	
	private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
	
	private ProfilePictureView profilePictureView;
    private TextView userNameView;
    
    private ArrayList<EventModel> eventList = new ArrayList<EventModel>();
	private ListView eventListView;
	private EventAdapter adapter;
	//private ImageView imageView;
	
	private String[] eventId = new String[100]/*{"1438202429725937","1406652422905842","565640940180194","229266407240395","1478980972328156"}*/;
	private String[][] tags = new String[100][20]/*{{"1","1","1"},{"2","2","1"},{"3","3","1"},{"4","4","1"},{"5","5","1"},{"6","6","1"}}*/;
	
	private int descriptionCount = 0;
	private int number = 0;
	private int count = 0;
	private int eventPosition = 0;
	private int show=0;
	private int logOut = 0;
	private int getEventId = 0;
	private int listPosition;
	private int eventItemNumber = 0; 
	private int eventListEnd = 0;
	
	private EventModel lastEvent;
	
	private boolean checkLike = false;
	private boolean checkJoin = false;
	
	private String userId;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);

	    setContentView(R.layout.activity_main);
	    
	    /*LayoutInflater inflater = this.getLayoutInflater();
	    View view = inflater.inflate(R.layout.activity_main,null);*/

	    // Find the user's profile picture custom view
		profilePictureView = (ProfilePictureView) findViewById(R.id.profile_pic);
	
		// Find the user's name view
		userNameView = (TextView) findViewById(R.id.user_name);
		Log.i("ib","ib");
	    

	    FragmentManager fm = getSupportFragmentManager();
	    fragments[SPLASH] = fm.findFragmentById(R.id.splashFragment);
	    fragments[SELECTION] = fm.findFragmentById(R.id.selectionFragment);
	    fragments[SETTINGS] = fm.findFragmentById(R.id.userSettingsFragment);

	    FragmentTransaction transaction = fm.beginTransaction();
	    for(int i = 0; i < fragments.length; i++) {
	        transaction.hide(fragments[i]);
	    }
	    transaction.commit();
	    
	    eventListView = (ListView) findViewById(R.id.EventListView);
        
	    
        // create a custom adapter and set to the list view
        adapter = new EventAdapter(this, eventList);
        eventListView.setAdapter(adapter);
        //showEvents();
        Log.i("cow","cow");
        System.out.println("cow");
        new Thread(){
        	@Override
        	public void run(){
        		Log.i("create","fuck");
        		System.out.println("fuck");
        		getEventId("http://event-teller.appspot.com/searchevent");
        	}
        }.start();
        
        addItemClickListener();
        
	}
	private void getEventId(String url){
    	HttpPost request = new HttpPost(url);
    	request.addHeader("Content-Type", "application/json");
		JSONObject note = new JSONObject();
		try {
			note.put("keyword","");
			note.put("tag",null);
			note.put("sort_by","start_time");
			Log.i("afterPost",note.toString());
		    request.setEntity(new StringEntity(note.toString()));
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			System.out.println(httpResponse.getStatusLine().getStatusCode());
			String s = EntityUtils.toString(httpResponse.getEntity());
			s = s.replace("%", "\\");
			String retSrc = URLDecoder.decode(s, "UTF-8");
			Log.i("Post",retSrc);
			JSONObject response = new JSONObject(retSrc);
			JSONArray data = response.getJSONArray("events");
			for(int i=0;i<data.length();i++){
				eventId[i] = data.getJSONObject(i).getString("id");
				int number = data.getJSONObject(i).getJSONArray("tag").length();
				for(int j=0;j<number;j++){
					tags[i][j] = data.getJSONObject(i).getJSONArray("tag").getJSONObject(j).getString("value");
				}
			}
			getEventId = 1;
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void showFragment(int fragmentIndex, boolean addToBackStack) {
	    FragmentManager fm = getSupportFragmentManager();
	    FragmentTransaction transaction = fm.beginTransaction();
	    for (int i = 0; i < fragments.length; i++) {
	        if (i == fragmentIndex) {
	            transaction.show(fragments[i]);
	        } else {
	            transaction.hide(fragments[i]);
	        }
	    }
	    if (addToBackStack) {
	        transaction.addToBackStack(null);
	    }
	    transaction.commit();
	}
	
	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
	    // Only make changes if the activity is visible
	    if (isResumed) {
	        FragmentManager manager = getSupportFragmentManager();
	        // Get the number of entries in the back stack
	        int backStackSize = manager.getBackStackEntryCount();
	        // Clear the back stack
	        for (int i = 0; i < backStackSize; i++) {
	            manager.popBackStack();
	        }
	        if (state.isOpened()) {
	            // If the session state is open:
	            // Show the authenticated fragment
	        	//makeMeRequest(session);
	            /*showFragment(SELECTION, false);
	            FragmentTransaction transaction = manager.beginTransaction();
	            transaction.hide(fragments[1]);
	            transaction.commit();*/
	        	FragmentManager fm = getSupportFragmentManager();
	        	FragmentTransaction transaction = fm.beginTransaction();
	     	    for(int i = 0; i < fragments.length; i++) {
	     	        transaction.hide(fragments[i]);
	     	    }
	     	    transaction.commit();
	            //showEvents();
	     	    invalidateOptionsMenu();
	     	    logOut = 1;
	            Log.i("onSessionStateChange","done");
	        } else if (state.isClosed()) {
	            // If the session state is closed:
	            // Show the login fragment
	            showFragment(SPLASH, false);
	            invalidateOptionsMenu();
	        }
	    }
	}
	
	@Override
	protected void onResumeFragments() {

	    super.onResumeFragments();
	    Session session = Session.getActiveSession();

	    if (session != null && session.isOpened()) {
	        // if the session is already open,
	        // try to show the selection fragment
	    	makeMeRequest(session);
	        showFragment(SELECTION, false);
	        FragmentManager manager = getSupportFragmentManager();
	        FragmentTransaction transaction = manager.beginTransaction();
            transaction.hide(fragments[1]);
            transaction.commit();
            eventList.clear();
            showEvents();
            Log.i("onResumeFragments","done");
            invalidateOptionsMenu();
            logOut = 1;
	    } else {
	        // otherwise present the splash screen
	        // and ask the person to login.
	        showFragment(SPLASH, false);
	        invalidateOptionsMenu();
	    }
	}
	
	@Override
	public void onResume() {
	    super.onResume();
	    uiHelper.onResume();
	    isResumed = true;
	}

	@Override
	public void onPause() {
	    super.onPause();
	    uiHelper.onPause();
	    isResumed = false;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    uiHelper.onActivityResult(requestCode, resultCode, data);
	    /*if(requestCode == 0){  
	    	  if(resultCode==RESULT_OK){  
	    		  Bundle extras = data.getExtras();  
	    		  if (extras != null){
	    			 eventListView.getItemAtPosition(listPosition);
	    	      }  
	    	     
	    	  }  
	    }  */
	}

	@Override
	public void onDestroy() {
	    super.onDestroy();
	    uiHelper.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    uiHelper.onSaveInstanceState(outState);
	}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        log_out = menu.findItem(R.id.log_out);
        sort = menu.findItem(R.id.sort);
        return true;
    }
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // only add the menu when the selection fragment is showing
        if (fragments[SPLASH].isVisible() || fragments[SETTINGS].isVisible()) {
            //if (menu.size() == 0) {
                //log_out = menu.add(R.string.log_out);
                //sort = menu.add(R.string.sort);
        		Log.i("menu", "gonot");
                log_out.setVisible(false);
                log_out.setEnabled(false);
                sort.setVisible(false);
                sort.setEnabled(false);
            //}
            return true;
        } else {
            /*menu.clear();
            log_out = null;*/
        	Log.i("menu", "gogo");
        	log_out.setVisible(true);
            log_out.setEnabled(true);
            sort.setVisible(true);
            sort.setEnabled(true);
        }
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.equals(log_out)) {
            showFragment(SETTINGS, true);
            invalidateOptionsMenu();
            logOut = 0;
            return true;
        }
        else if (item.equals(sort)) {
        	if(logOut == 1){
        		showSortDialog();
        	}
        	invalidateOptionsMenu();
            return true;
        }
        return false;
    }
    private void makeMeRequest(final Session session) {
        // Make an API call to get user data and define a 
        // new callback to handle the response.
        Request request = Request.newMeRequest(session, 
                new Request.GraphUserCallback() {
            @Override
            public void onCompleted(GraphUser user, Response response) {
                // If the response is successful
                if (session == Session.getActiveSession()) {
                    if (user != null) {
                    	userId = user.getId();
                        // Set the id for the ProfilePictureView
                        // view that in turn displays the profile picture.
                        profilePictureView.setProfileId(user.getId());
                        Log.i("id", user.getId());
                        // Set the Textview's text to the user's name.
                        userNameView.setText(user.getName());
                    }
                }
                if (response.getError() != null) {
                    // Handle errors, will do so later.
                }
            }
        });
        request.executeAsync();
    }
    private void showSortDialog(){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle(R.string.sort_by);
    	builder.setItems(R.array.sort_array, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            // The 'which' argument contains the index position
            // of the selected item
            showFragment(SETTINGS, true);
            }
    	});
    	AlertDialog alert = builder.create();
    	alert.show();
    }
    private void showEvents(){
    	/*new Thread(){
        	@Override
        	public void run(){
        		
        		
        	}
        }.start();*/
    	while(getEventId == 0){
    		SystemClock.sleep(500);
    	}
    	Session session = Session.getActiveSession();
    	for(int i=0;i<eventId.length;i++){
    		if(eventId[i] == null){
    			eventListEnd = i - 1;
    			break;
    		}
    		EventModel event = new EventModel();
    		lastEvent = event;
    		eventList.add(event);
    		//Log.i("eventId",eventId[i]);
    		makeEventRequest(session,eventId[i],i);
    		eventItemNumber++;
    		count++;
    	}
    	/*new Thread(){
        	@Override
        	public void run(){
        		
        		//SystemClock.sleep(10000);
        		
        		MainActivity.this.runOnUiThread(new Runnable(){
        			@Override
        			public void run() {
        				
        				//eventList.clear();
        				adapter.notifyDataSetChanged();
        			}
        		});
        	}
        }.start();*/
        show = 0;
    	number = 0;
    	eventPosition = 0;
    	eventItemNumber = 0;
    	//getEventId = 0;
    	//Log.i("showEvents","middle");
    	descriptionCount = 0;
    	//System.out.println("count: "+ count );
    	//System.out.println("eventListsize: "+ eventList.size());
    	count = 0;
    }
    private int makeEventRequest(final Session session,  String id,final int counter) {
    	Log.i("fuck","fuck");
        // Make an API call to get user data and define a
        // new callback to handle the response.
    	int j=0;
    	Bundle params = new Bundle();
    	//System.out.println(1);
    	final EventModel eventModel = lastEvent;
    	final int number = eventItemNumber;
    	params.putString("fields", "id,name,picture,start_time,location,description");
    	System.out.println("1"+" id: "+id);
    	new Request(
    		    session,
    		    "/"+id,
    		    params,
    		    HttpMethod.GET,
    		    new Request.Callback() {
    		    	
    		       public void onCompleted( final Response response) {
    		    	   final int num = number;
    		    	   final EventModel evt = eventModel;
    		        	//GraphObject go  = response.getGraphObject();
    		           //JSONObject  jso = go.getInnerJSONObject();
    		            //new DownloadImageTask().execute(jso);
    		            // handle the result 
    		    	   //GraphObject go  = response.getGraphObject();
   		            	//JSONObject  jso = go.getInnerJSONObject();
   		            	
						/*try {
							String id = jso.getString("id");
							//System.out.println("2"+" id: "+id);
						} catch (JSONException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}*/
    		    	   
    		        	try
    		            {
    		        		
        		        	new Thread(){
        		            	@Override
        		            	public void run(){
        		            			
        		            		try{
        		            			GraphObject go  = response.getGraphObject();
            	    		            JSONObject  jso = go.getInnerJSONObject();
            	    		            //Log.i("url",jso.getJSONObject("picture").getJSONObject("data").getString("url"));
            	    		            //Log.i("name",jso.getString("name"));
            	    		            //Log.i("event response",jso.toString());
            	    		            String date = "Date: ";
            	    		            String time = "Time: ";
            	    		            String location = "Location: ";
            	    		            String tag = "Tags: ";
            	    		            String[] startTimeOneSplit = jso.getString("start_time").split(Pattern.quote("+"));
            	    		            String[] startTimeTwoSplit = startTimeOneSplit[0].split("T");
            	    		            date = date + startTimeTwoSplit[0];
            	    		            time = time + startTimeTwoSplit[1];
            	    		            location = location + jso.getString("location");
            	    		            int n = num;
            	    		            EventModel event = evt;
            	    		            //EventModel event = new EventModel();
            	    		            
            	        		        event.setName(jso.getString("name"));
            	        		        event.setDate(date);
            	        		        event.setTime(time);
            	        		        event.setLocation(location);
            	        		        event.setDescription(jso.getString("description"));
            	        		        tag = tag + tags[n][0];
            	        		        for(int i=1;i<tags[n].length;i++){
            	        		        	if(tags[n][i] == null){
            	        		        		break;
            	        		        	}
            	        		        	tag = tag + " , " + tags[n][i];
            	        		        }
            	        		        event.setTags(tag);
            	        		        String urlString = jso.getJSONObject("picture").getJSONObject("data").getString("url");
            	        		        URL url = new URL(urlString);
            	        		        URLConnection conn = url.openConnection();
            	        		        HttpURLConnection httpConn = (HttpURLConnection)conn;
            	        		        httpConn.setRequestMethod("GET");
            	        		        httpConn.connect();
            	        		        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            	        		        	
            	        		            InputStream inputStream = httpConn.getInputStream();
            	        		            byte[] bytes = IOUtils.toByteArray(inputStream);
            	        		            inputStream.close();
            	        		            event.setImage(bytes);
            	        		        }
            	        		        String id = jso.getString("id");
            	        		        /*Log.i("id",id);
            	        		        for(int i=0;i<eventId.length;i++){
            	        		        	if(id == eventId[i]){
            	        		        		eventList.set(i, event);
            	        		        				
            	        		        	}
            	        		        }*/
            	        		        //eventList.add(event);
            	        		        eventPosition++;
                	        		    
                	        		    //System.out.println("3"+" id: "+id);
            	        		        /*description[descriptionCount] = jso.getString("description");
            	        		        descriptionCount++;*/
            	        		        show++;
        		            		}
        		            		catch ( Exception e )
        		    		        {
        		    		                e.printStackTrace();
        		    		        }
        		            		
        		            		if(show == eventListEnd){
        		            			MainActivity.this.runOnUiThread(new Runnable(){
            		            			@Override
            		            			public void run() {
            		            				
            		            				adapter.notifyDataSetChanged();
            		            			}
            		            		});
        		            		}
        		            	}
        		            }.start();
        		            	
        		            		
        		             
    		            }
    		            catch ( Exception e )
    		            {
    		                e.printStackTrace();
    		            }
    		        	
    		        	
    		        	//Log.i("makeEventRequest",response.getConnection().toString());
    		        	//Log.i("makeEventRequest",response.toString());
    		        	//Log.i("makeEventRequest",response.getRequest().toString());
    		        }
    		    }
    		).executeAsync();
    	j=1;
    	return j;
    }
    private void addItemClickListener(){
    	eventListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	
            	listPosition = position;
                /*String title = ((TextView)view.findViewById(R.id.event_name)).getText().toString();
                
                Toast.makeText(getBaseContext(), title, Toast.LENGTH_SHORT).show();*/
            	//Log.i("addItemClickListener","fist line");
            	final Switch like = (Switch) view.findViewById(R.id.event_switch_like);
            	Log.i("like","start");
            	like.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            	    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            	        if (isChecked) {
            	        	checkLike = true;
            	        	like.setChecked(true);
            	        	Log.i("like","true");
            	            // The toggle is enabled
            	        } else {
            	        	checkLike = false;
            	        	Log.i("like","false");
            	            // The toggle is disabled
            	        }
            	    }
            	});
            	if(like.isChecked()){
            		checkLike = true;
            		like.setChecked(true);
    	        	Log.i("like","true");
            	}
            	else{
            		checkLike = false;
          	        Log.i("like","false");
            	}
            	Switch join = (Switch) view.findViewById(R.id.event_switch_join);
            	join.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            	    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            	        if (isChecked) {
            	        	checkJoin = true;
            	            // The toggle is enabled
            	        } else {
            	        	checkJoin = false;
            	            // The toggle is disabled
            	        }
            	    }
            	});
            	if(join.isChecked()){
            		checkJoin = true;
    	        	Log.i("join","true");
            	}
            	else{
            		checkJoin = false;
          	        Log.i("join","false");
            	}
                Intent intent = new Intent(view.getContext(), EventDisplayMessageActivity.class);
                //Log.i("addItemClickListener","start");
                TextView name = (TextView) view.findViewById(R.id.event_name);
                TextView date = (TextView) view.findViewById(R.id.event_start_date);
                TextView time = (TextView) view.findViewById(R.id.event_start_time);
                TextView location = (TextView) view.findViewById(R.id.event_location);
                TextView description = (TextView) view.findViewById(R.id.event_description);
                ImageView imageView = (ImageView) view.findViewById(R.id.event_picture);
                /*Log.i("addItemClickListener","start1");
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), image.getId());
                Log.i("addItemClickListener","start2");
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                Log.i("addItemClickListener","start3");
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
                Log.i("addItemClickListener","start4");
                byte[] bytes = stream.toByteArray();*/
                imageView.buildDrawingCache();
                Bitmap image= imageView.getDrawingCache();
                Bundle extras = new Bundle();
                extras.putParcelable("imagebitmap", image);
                //Log.i("addItemClickListener","middle");
                intent.putExtra("name", name.getText().toString());
                intent.putExtra("date", date.getText().toString());
                intent.putExtra("time", time.getText().toString());
                intent.putExtra("location", location.getText().toString());
                intent.putExtra("description", description.getText().toString());
                //intent.putExtra("description",description[position]);
                intent.putExtras(extras);
                intent.putExtra("like", checkLike);
                intent.putExtra("join", checkJoin);
                //Log.i("addItemClickListener","last");
                System.out.println(position);
                System.out.println("like: "+ checkLike);
                System.out.println("join: "+ checkJoin);
                startActivity(intent);
            }
        });
    }
    /*private class DownloadImageTask extends AsyncTask<JSONObject, Void, EventModel> {
	    // The system calls this to perform work in a worker thread and
	     // delivers it the parameters given to AsyncTask.execute() 
	    protected EventModel doInBackground(JSONObject... jso) {
	    	try{
	    		String date = "Date: ";
	    		String time = "Time: ";
	            String location = "Location: ";
	            String[] startTimeOneSplit = jso[0].getString("start_time").split(Pattern.quote("+"));
	            String[] startTimeTwoSplit = startTimeOneSplit[0].split("T");
	            date = date + startTimeTwoSplit[0];
	            time = time + startTimeTwoSplit[1];
	            location = location + jso[0].getString("location");
	            //EventModel event = new EventModel();
	            eventTest = new EventModel();
		        eventTest.setName(jso[0].getString("name"));
		        eventTest.setDate(date);
		        eventTest.setTime(time);
		        eventTest.setLocation(location);
		        String urlString = jso[0].getJSONObject("picture").getJSONObject("data").getString("url");
		        URL url = new URL(urlString);
		        URLConnection conn = url.openConnection();

		        HttpURLConnection httpConn = (HttpURLConnection)conn;
		        httpConn.setRequestMethod("GET");
		        httpConn.connect();
		        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
		            InputStream inputStream = httpConn.getInputStream();
		            byte[] bytes = IOUtils.toByteArray(inputStream);
		            inputStream.close();
		            eventTest.setImage(bytes);
		        }
		       
		        eventList.add(eventPosition,eventTest);
		        eventPosition++;
			    number++;
			    System.out.println("number: "+number + " id: "+jso[0].getString("id"));
		        description[descriptionCount] = jso[0].getString("description");
		        descriptionCount++;
	    	}
	    	catch ( Exception e )
	        {
	                e.printStackTrace();
	        }
			return eventTest;
	    }
	    
	    // The system calls this to perform work in the UI thread and delivers
	    //   the result from doInBackground() 
	    protected void onPostExecute(EventModel event) {
	    	
	    	adapter.notifyDataSetChanged();
	    }

	}*/
}
